package main

import (
	"log"
	"net"
	"net/rpc"
	"time"
)

// 算数运算结构体
type Arith struct {
}

// 算数运算请求结构体
type ArithRequest struct {
	A int
	B int
}

// 算数运算响应结构体
type ArithResponse struct {

	Result int
}


// 加法运算方法
func (this *Arith) Add(req ArithRequest, res *ArithResponse) error {
	res.Result = req.A + req.B
	return nil
}

var Close_done_chan = make(chan int, 1)
var Close_chan = make(chan int, 1)

func main(){
	addr := "127.0.0.1:8007"
	tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
	if err != nil {
		log.Fatalf("rpc.Start error, net.ResolveTCPAddr failed, %s", err)
	}
	listener, err := net.ListenTCP("tcp", tcpAddr)
	if err != nil {
		log.Fatalf("rpc.Start error, listen %s failed, %s", addr, err)
	} else {
		log.Println("rpc.Start ok, listening on", addr)
	}
	rpc.Register(new(Arith))

	go func() {
		var tempDelay time.Duration // how long to sleep on accept failure
		for {
			conn, err := listener.Accept()
			if err != nil {
				if tempDelay == 0 {
					tempDelay = 5 * time.Millisecond
				} else {
					tempDelay *= 2
				}
				if max := 1 * time.Second; tempDelay > max {
					tempDelay = max
				}
				time.Sleep(tempDelay)
				continue
			}
			tempDelay = 0
			go func() {

				rpc.ServeConn(conn)
			}()
		}
	}()

	select {
	case <-Close_chan:
		log.Println("rpc, recv sigout and exiting...")
		listener.Close()
		Close_done_chan <- 1

		return
	}

}